﻿# -*- coding:utf-8 -*-

import datetime, os

from django import forms
from django.conf import settings
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404  #, get_object_or_403
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils import simplejson 
from django.contrib import messages
from django.contrib.sites.models import Site
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.forms.models import model_to_dict

from django.template import RequestContext, Context
from django.core import serializers
from django.core.urlresolvers import reverse

from models import Plugin, Agent, Task, AgentLog, TaskField, TaskFieldValue, TaskQueue
from forms import CreateTaskQueueForm
from pcadmin import settings as shmadmin_settings


def getTransliterateFilename(file_field):
    import pcadmin.trans
    basename, format = os.path.splitext(file_field)
    return u'%s%s' %  (basename.encode('trans/slug'),format)
    

def handle_uploaded_file(f):
    trl_name = getTransliterateFilename(f.name)
    name = trl_name
    path = u'%s/%s' % (settings.MEDIA_ROOT, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR)
    file_path = os.path.join(path, trl_name)
    i = 0
    while os.path.exists(file_path):
        name = u'%s_%i' % (trl_name, i)
        file_path = os.path.join(path, name)
        i = i + 1
        if i > 1000:
            pass    
    destination = open(file_path, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    site = Site.objects.get(id=settings.SITE_ID).domain
    return u'%s%s' % (site, os.path.join(settings.MEDIA_URL, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR, name))


def render_to(request, template, context):
    context_extra = Context({
    })
    return render_to_response(u"pcadmin/%s" % template, context, context_instance=RequestContext(request, context_extra))
        
    
    

def get_task_json(request):   
    '''
    [
        {
            "code": "CORE_SHOW_MESSAGE",
            "description": "", 
            "title": "Показать сообщение ", 
            "start": "2012-04-11 15:02:12", 
            "id": 1, 
            "taskparam": 
            [
                {
                    "value": "парамеир для команды",
                    "key": "test"
                },
                
                {
                    "value": "Выводимое сообщение",
                    "key": "message"
                }
            ]
        }, 
    ]
    '''
    try:
        apid = request.GET['apid']
        passkey =  request.GET['passkey']
    except:
        return HttpResponse('Error: param required.', status = 501)     
    
    if not Agent.objects.filter(apid=apid, passkey=passkey).exists():
        return HttpResponse('Error: auth.', status = 401)  
    #
    agent = get_object_or_404(Agent, apid=apid, passkey=passkey)
    agent.last_conn_date = datetime.datetime.now()
    agent.last_ip = request.META.get('REMOTE_ADDR')
    agent.save()     
    #
    task_queue = TaskQueue.objects.select_related().filter(agent = agent, done=False)
    result = []
    for item in task_queue: 
        result.append({"id" : item.id,
                        "code" : item.task.code,
                        "start" : u"%s" % item.start.strftime('%m/%d/%y %H:%M:%S') ,
                        "interval" : item.task.interval,
                        "title" : item.task.title,
                        "description" : item.task.description,
                        "taskparam" : [{"key":i.taskfield.name, "value":i.value} for i in item.taskfieldvalue_set.all() ],
                        })     
    return HttpResponse(simplejson.dumps(result, ensure_ascii=False))
  

def set_task_acknowledge(request):
    if request.method == 'POST':
        try:
            apid = request.POST['apid']
            passkey =  request.POST['passkey']
            taskid = request.POST['task']
        except:
            return HttpResponse('Error: param required.', status = 501)    

        if not Agent.objects.filter(apid=apid, passkey=passkey).exists():
            return HttpResponse('Error: auth.', status = 401)
       
        task_queue = get_object_or_404(TaskQueue, id = taskid) 
        task_queue.acknowledge = True;
        task_queue.save()
    
        return HttpResponse('ok', status = 200)
    return HttpResponse('Error: get not support.', status = 501)


  

def set_log_message(request):
    if request.method == 'POST':
        try:
            apid = request.POST['apid']
            taskid = request.POST['task']
            message = request.POST['message']
            code = request.POST['code']
            agentdate = request.POST['localtime']
        except:
            return HttpResponse('Error: param required.', status = 501)
        data = request.POST.get('data', default='')     
        #   
        agent = get_object_or_404(Agent, apid = apid)
        if taskid == 'None':
            task_queue = None
        else:
            task_queue = get_object_or_404(TaskQueue, id = taskid)
            task_queue.done = True
            task_queue.save() 
        agentlog = AgentLog(agent=agent, task=task_queue, message=message, code='M', data = data, agentdate = agentdate)#datetime.datetime.now())
        agentlog.save()
        return HttpResponse('ok', status = 200)
    return HttpResponse('Error: get not support.', status = 501)


def get_apid_json(request):   
    '''
    [
        {
            "apid": "APID1290028912",
        }, 
        {
            "apid": "APID5658440309",
        }, 
        ...
    ]
    '''
    try:
        passkey =  request.GET['passkey']
    except:
        return HttpResponse('Error: param required.', status = 501)     
 
    agent_list =  Agent.objects.all()
    result = [{"apid" : agent.apid} for agent in agent_list]
    return HttpResponse(simplejson.dumps(result, ensure_ascii=False))


def module_rdv_upload(request):    
    if request.method == 'POST':
        try:
            f = request.FILES['imagefile']
            name = getTransliterateFilename(f.name)
            path = u'%s/%s' % (settings.MEDIA_ROOT, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR)
            file_path = os.path.join(path, name)
            destination = open(file_path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            site = Site.objects.get(id=settings.SITE_ID).domain
            #img_url = u'%s%s' % (site, os.path.join(settings.MEDIA_URL, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR, name))
           
        except:       
            pass
              
    return HttpResponse('ok', status = 200)
    
    
    




@login_required
def pcadmin_index(request): 
    context = Context({
        'index_page':1,
    })
    return render_to(request, 'pcadmin_index.html', context)



@login_required
def agent_list(request): 
    agent_list =  Agent.objects.all()
    agent_list_ex = []
    for agent in agent_list:
        item_agent_dict = model_to_dict(agent)
        item_agent_dict['timeout'] = None
        item_agent_dict['state'] = False
        if item_agent_dict['last_conn_date']:
            agent_timeout = datetime.datetime.now() - item_agent_dict['last_conn_date']
            if agent_timeout < datetime.timedelta(0,0,0,2*int(item_agent_dict['conn_interval'])):
                item_agent_dict['state'] = True
            item_agent_dict['timeout'] = agent_timeout
        agent_list_ex.append(item_agent_dict)
    context = Context({
        'agent_list':agent_list_ex,
    }) 
    return render_to(request, 'agent_list.html', context)
    
    

@login_required
def agent_details(request, agent_id): 
    agent = get_object_or_404(Agent, id = agent_id)
    task_list = Task.objects.all()
    context = Context({
        'agent':agent,
        'task_list': task_list,
    })
    return render_to(request, 'agent_details.html', context)    
    
    
    
@login_required    
def get_loglist_ajax(request, agent_id):
    try:    
        agent = Agent.objects.get(id = agent_id)
        log_list = AgentLog.objects.filter(agent = agent)[:25]
    except:
        log_list = AgentLog.objects.all()[:25]
    context = Context({
        'log_list':log_list,
    })
    return render_to(request, 'log_list.html', context)    



@login_required
def get_task_loglist_ajax(request, task_id):
    log_list = AgentLog.objects.filter(task = task_id)[:25]
    context = Context({
        'log_list':log_list,
    })
    return render_to(request, 'log_list.html', context)



@login_required
def log_details(request, log_id):
    log_item = get_object_or_404(AgentLog, id=log_id)
    context = Context({
        'log_item':log_item,
    })
    return render_to(request, 'log_details.html', context)  



@login_required
def task_list(request):
    task_list = Task.objects.all()
    agent_list =  Agent.objects.all() 
    task_queue = TaskQueue.objects.all().order_by('-start')[:25]
    context = Context({
        'task_list':task_list,
        'agent_list':agent_list,   
        'task_queue':task_queue,     
    })
    return render_to(request, 'task_list.html', context)



@login_required
def create_task_queue(request, task_id):
    task = get_object_or_404(Task, id = task_id) 
    try:
      agent_id = int(request.GET.get('agent'))    
    except:  
      agent_id = None
      
    agent_list =  Agent.objects.all()
    if request.method == 'POST':
        form = CreateTaskQueueForm(task, request.POST, request.FILES)
        # список отмеченных агентов
        agent_checked =  [Agent.objects.get(id = (x.replace('agent_id_', ''))) for x in request.POST if x.startswith('agent_id_')]  
        if len(agent_checked) == 0:
            messages.warning(request, 'Выберите хоть одного агента.')
        else:    
            if form.is_valid():
                for key, field in form.fields.items():
                    if field.__class__ == forms.FileField:
                        #print  key, field
                        fn = handle_uploaded_file(request.FILES[key])
                        form.cleaned_data[key] = fn
            
                for agent in agent_checked:
                    form.save(agent, request.user)
        
                messages.success(request, 'Задание добавлено в очередь.')
                return HttpResponseRedirect(reverse('create_task_queue', args=[task_id])) 
                #return HttpResponseRedirect(reverse('task_queue_item_details',args=[task_id])) 
    else:
        form = CreateTaskQueueForm(task)  
     
    context = Context({
        'form':form,
        'agent_list':agent_list,
        'task':task,
        'agent_selected':agent_id,
    })
    return render_to(request, 'create_task_queue.html', context)
    
    
    
@login_required  
def task_details(request):
    #task_list = Task.objects.all()
    #agent_list =  Agent.objects.all()    
    context = Context({
     #   'task_list':task_list,
     #   'agent_list':agent_list,        
    })
    return render_to(request, 'task_details.html', context)
    
    
    
@login_required 
def task_queue_item_details(request, id): 
    task_queue_item = get_object_or_404(TaskQueue, id = id) 
    context = Context({
        'item':task_queue_item,   
    })
    return render_to(request, 'task_queue_item_details.html', context)
    
    
@login_required 
def module_rdv_view(request):
 
    context = Context({
    })
    return render_to(request, 'module_rdv_view.html', context) 
 
 

 
'''  
def module_rdv_upload(request):    
    if request.method == 'POST':
        try:
            f = request.FILES['imagefile']
            name = getTransliterateFilename(f.name)
            path = u'%s/%s' % (settings.MEDIA_ROOT, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR)
            file_path = os.path.join(path, name)
            destination = open(file_path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            site = Site.objects.get(id=settings.SITE_ID).domain
            #img_url = u'%s%s' % (site, os.path.join(settings.MEDIA_URL, shmadmin_settings.SHMADMIN_FILE_UPLOAD_DIR, name))
           
        except:       
            pass
              
    return HttpResponse('ok', status = 200)
    
'''
    
    
    
    
    